﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using TransControlSystem.Dao;
using TransControlSystem.Model;

namespace TransControlSystem.ViewModel.Common
{
    /// <summary>
    /// 操作日志工具
    /// </summary>
    public static class LogTool
    {
        //当前登录的用户
        public static User CurrentUser;
        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="OperName">操作名称</param>
        /// <param name="OperContent">操作内容</param>
        public static int SaveLog(string OperName, string OperContent)
        {
            Log SaveLog = new Log
            {
                OperName = OperName,
                OperContent = OperContent,
                OperTime = DateTime.Now
            };
            if (CurrentUser != null)
            {
                SaveLog.UserName = CurrentUser.UserName;
            }
            else
            {
                SaveLog.UserName = "";
            }
            try
            {
                //使用外网获取IP
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
                {
                    socket.Connect("8.8.8.8", 65530);
                    IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                    SaveLog.OperIp = endPoint.Address.ToString();
                }
            }
            catch (Exception e)
            {
                //获取内网IP 
                SaveLog.OperIp = GetLocalIPAddress();
                SaveSysLog(e.Message, "获取IP地址异常");
            }
            int OrderNo = DapperTools.Query<Log>("select MAX(OrderNo) AS OrderNo from [Log]", SaveLog).OrderNo;
            SaveLog.OrderNo = OrderNo + 1;

            string Sql = @"insert [Log] (
                                       [OrderNo]
                                      ,[UserName]
                                      ,[OperName]
                                      ,[OperContent]
                                      ,[OperTime]
                                      ,[OperIp]
                                     ) values (
                                       @OrderNo,
                                       @UserName,
                                       @OperName,
                                       @OperContent,
                                       @OperTime,
                                       @OperIp
                                    )";
            int result = DapperTools.Add(Sql, SaveLog);
            return result;
        }
        /// <summary>
        /// 获取内网IP
        /// </summary>
        /// <returns></returns>
        private static string GetLocalIPAddress()
        {
            try
            {
                string hostName = Dns.GetHostName();
                IPHostEntry iPHostEntry = Dns.GetHostEntry(hostName);
                var addressV = iPHostEntry.AddressList.FirstOrDefault(q => q.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);//ip4地址

                if (addressV != null)
                {
                    return addressV.ToString();
                }
                else
                {
                    return "127.0.0.1";
                }
            }
            catch (Exception ex)
            {
                SaveSysLog(ex.Message, "获取IP地址异常");
                return "127.0.0.1";
            }
        }
        /// <summary>
        /// 记录系统运行日志
        /// </summary>
        /// <param name="LogContent"></param>
        public static void SaveSysLog(string LogContent, string Type)
        {
            string LogFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".LOG";
            if (false == Directory.Exists(Environment.CurrentDirectory + "\\Log"))
            {
                Directory.CreateDirectory(Environment.CurrentDirectory + "\\Log");
            }
            string LogFilePath = Environment.CurrentDirectory + "\\Log\\" + LogFileName;
            FileStream fs = new FileStream(LogFilePath, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
            Type = "【" + Type + "】";
            sw.Write(DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss dddd") + "    " + Type + "：" + LogContent + "\r\n");
            sw.Close();
            fs.Close();
        }
    }
}
